<?php
/*
 * @Author: 李志刚
 * @CopyRight: 2020-2030 衡水山木枝技术服务有限公司
 * @Date: 2021-09-14 09:14:33
 * @Description: 权限菜单管理
 * @LastEditors: 李志刚
 * @LastEditTime: 2021-09-14 09:24:33
 * @FilePath: /qingshanERP/app/Http/Controllers/Tenant/MenuController.php
 */

namespace App\Http\Controllers\Tenant;

use Illuminate\Http\Request;
use App\Models\Tenant\TenantMenu;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redis;

class MenuController extends Controller
{
    // 取左侧权限菜单
    public function getList(Request $request)
    {
        try {
            // 一级菜单
            $all = TenantMenu::select('id', 'parentid', 'name', 'url', 'icon', 'label')->where('display', '=', '1')->orderBy('sort', 'asc')->orderBy('id', 'asc')->get();
            $leftmenu = [];
            // 判断权限
            $left = $all->where('parentid', 0)->all();
            // 取到用户信息
            $token = $request->header('Authorization');
            $token_info = Redis::get('t-token:' . $token);
            // 解析用户信息，判断权限
            $user = json_decode($token_info);
            // 判断权限
            if ($request->tenant->super) {
                $user->allPriv = $all->pluck('label')->unique()->toArray();
            }else {
                $user->allPriv = $all->pluck('label')->unique()->toArray();
            }
            // 一级循环
            foreach ($left as $k => $v) {
                foreach ($user->allPriv as $url) {
                    if ($v['label'] == $url) {
                        $leftmenu[$k] = $v;
                    }
                }
            }
            // 二级菜单
            foreach ($leftmenu as $k => $v) {
                // 取所有下级菜单
                $submenu = $all->where('parentid', '=', $v['id'])->all();
                $childSubMenu = [];
                foreach ($submenu as $s => $v) {
                    if (in_array($v['label'], (array) $user->allPriv)) {
                        $childSubMenu[$s] = $v;
                    }
                }
                $leftmenu[$k]['submenu'] = $childSubMenu;
            }
            // return $this->resData(200, '获取成功...', $leftmenu);
            // 三级菜单
            foreach ($leftmenu as $k => $v) {
                $submenu = $v['submenu'];
                // 所有二级
                foreach ($submenu as $s => $sub) {
                    // 取所有下级菜单
                    $there = $all->where('parentid', '=', $sub['id'])->all();
                    $thereSubMenu = [];
                    foreach ($there as $t => $v) {
                        if (in_array($v['label'], (array) $user->allPriv)) {
                            $thereSubMenu[$t] = $v;
                        }
                    }
                    $submenu[$s]['there'] = $thereSubMenu;
                }
                $leftmenu[$k]['submenu'] = $submenu;
            }
            return $this->resData(200, '获取成功...', $leftmenu);
        } catch (\Throwable $e) {
            return $this->resData(500, '获取失败，请稍后再试...');
        }
    }
}
